/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package kotionokyurievna.gmail.com.bankproject.logic;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Kateryna_Reznik
 */
public class Bank{
    private List<Account> accounts;
        
    public Bank(){
        accounts = new ArrayList<>();
    }
    public void transfer(int accountFrom, int accountTo, int amount){
        Account from = accounts.get(accountFrom);
        Account to = accounts.get(accountTo);
        try{
            if (from.tryLock()){
                try{
                    if (to.tryLock()){
                        if (from.withdraw(amount)){
                            to.deposit(amount);
                        }  
                    }
                }
                catch (InterruptedException iex){
                    System.err.println(iex);
                }
                finally{
                    to.unlock();
                }
            }
        }
        catch (InterruptedException iex){
            System.err.println(iex);
        }
        finally{
            from.unlock();
        }
    }
        
    public void addAccount( Account account ){
        accounts.add(account);
    }
        
    public int getAccountsNumber(){
        return accounts.size();
    }
    
    public Account getAccount ( int index ){
        int count = getAccountsNumber();
        if ( index < count && index >= 0 ){
            return accounts.get(index);
        } 
        else{
           throw new IndexOutOfBoundsException();
        }
    }
    
    public int getBallance(){
        int ballance = 0;
        for ( Account a: accounts ){
            ballance += a.getSum();
        }
        return ballance;
    }

    @Override
    public String toString() {
        return "Bank{" + "accounts=" + accounts + '}';
    }
        
        
}

